<?php

class EstadoMapper extends SON_Db_DataMapperAbstract
{
    protected $_dbTable = "DbTable_Estado";
    protected $_model = "Estado";

    protected function _insert(SON_Db_DomainObjectAbstract $obj)
    {
        try {
            $dbTable = $this->getDbTable();
            $data = array(
                'sigla' => $obj->getSigla(),
                'nome' => $obj->getNome()
            );
            return $dbTable->insert($data);
        } catch (Zend_Exception $e) {
            throw new Exception($e);
        }
    }

    protected function _update(SON_Db_DomainObjectAbstract $obj)
    {
        try {
            $dbTable = $this->getDbTable();
            $data = array(
                'sigla' => $obj->getSigla(),
                'nome' => $obj->getNome()
            );
            $data = array_map(function($value) { return (!is_null($value) && empty($value)) ? new Zend_Db_Expr('NULL') : $value; }, $data);
            $dbTable->update(array_filter($data), array('id = ?' => $obj->getId()));
            return true;
        } catch (Zend_Exception $e) {
            throw new Exception($e);
        }
    }
    
    public function fetchPairs()
    {
    	$select = $this->getDb()->select()->from('estado', array('id', 'nome'));
    	return $this->getDb()->fetchPairs($select);
    }
    
    public function findBySigla($sigla)
    {
    	$db = $this->getDb();
    	$query = $db->select();
    	$query->from('estado')
    		->where('sigla = ?', $sigla);
    
    	$data = $db->fetchRow($query);
    	if ($data) {
    		return $this->_populate($data);
    	}
    }
}

